<template>
    <div class="gl-upload-file-wrapper">
        <a-upload
            :fileList="filesList"
            :maxCount="getMaxCount"
            :accept="props.accept"
            :before-upload="beforeUpload"
            @change="handleChange"
            @remove="handleRemove"
        >
            <a-button>
                <UploadOutlined />
                {{  btnText  }}
            </a-button>
        </a-upload>
    </div>
</template>

<script setup lang="ts">
import { message, Upload } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';
interface Props { 
    value?: any[];
    maxCount?: number;
    accept?: string;
    btnText?: string;
    limitTypes?: string[];
}

const props = withDefaults(defineProps<Props>(), { 
    value: () => [],
    maxCount: 1,
    accept: '.png, .jpg, .jpeg, .svg .doc, .docx, .xls, xlsx, .pdf, .PDF, .PPT, .ppt, pptx, .txt, .bin, .gz, .zip, .rar, .md, .apk',
    btnText: '点击上传图片或文件',
    limitTypes: () => [],
});

const emit = defineEmits(['change']); // 抛出子组件事件

const getMaxCount = computed(()=> props.maxCount);

const filesList = ref<UploadProps['fileList']>([]);

const handleRemove: UploadProps['onRemove'] = file => {
    unref(filesList)?.length && unref(filesList)?.forEach((item: UploadChangeParam['file'], index: number) => {
        if(item?.uid == file?.uid){
            filesList.value?.splice(index, 1);
        }
    })
};

const beforeUpload: UploadProps['beforeUpload'] = file => {
    const { limitTypes } = props;
    console.log('文件：', file);
    if(limitTypes && limitTypes.length){
        const isPass = limitTypes.includes(file.type);
        if(!isPass){
            message.error('提示：文件格式不对!');
            return isPass || Upload.LIST_IGNORE;
        }
    }
    return false;
};

const handleChange = async({ fileList, file }: UploadChangeParam) => {
    filesList.value = fileList.map((item: Recordable) => {
        if(item?.originFileObj && Object.keys(item?.originFileObj).length){
            return item.originFileObj;
        }else{
            return item;
        }
    });
    emit('change', unref(filesList));
};
</script>

<style lang="less" scoped>
.gl-upload-file-wrapper {
    .ant-upload-select-picture-card i {
        font-size: 32px;
        color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
        margin-top: 8px;
        color: #666;
    }
}
</style>